package com.shanghaionstar.carmanage.chargpile;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.map.util.ToastUtil;
import com.onstar.cn.weight.CustomImageView;
import com.onstar.cn.weight.DeleteEditText;
import com.onstar.cn.weight.ProgressLayout;
import com.shanghaionstar.R;
import com.shanghaionstar.carmanage.ChargingPileActivity;
import com.shanghaionstar.carmanage.adapter.ChargePileStationListAdapter;
import com.shanghaionstar.carmanage.iview.IChargingPileView;
import com.shanghaionstar.carmanage.model.ChargePileStationEntity;
import com.shanghaionstar.carmanage.presenter.ChargingPilePresenter;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.weight.CommonNoDatasLayout;

import java.util.List;

/**
 * Created by 7828wc on 16/8/1.
 */
public class ChargingPileListFragment extends BaseFragment implements IChargingPileView {
    @FindViewById
    private CustomImageView left_btn_back;
    @FindViewById
    private DeleteEditText edit_search_addressinfo;
    @FindViewById
    private CommonNoDatasLayout no_datas_layout;
    @FindViewById
    private ProgressLayout loading_progress;
    @FindViewById
    private ListView station_list;
    @FindViewById
    private LinearLayout more_layout;
    @FindViewById
    private TextView tv_more;
    @FindViewById(R.id.brand_btn)
    private Button mBrandBtn;
    private ChargingPilePresenter presenter;
    private ChargingPileActivity parentActivity;
    private ChargePileStationListAdapter adapter;

    @Override
    public int getLayoutId() {
        return R.layout.car_manager_charging_pile_list;
    }

    boolean isFirst = true;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        btnBackClick(left_btn_back);
        edit_search_addressinfo.setHint(R.string.charging_pile_list);

        if (isCadillac()) {
            mBrandBtn.setText(R.string.charging_pile_cadillac);
        } else if (isBuick()) {
            mBrandBtn.setText(R.string.charging_pile_buick);
        } else {
            mBrandBtn.setVisibility(View.GONE);
        }


        initListener();

        if (isFirst) {
            parentActivity = (ChargingPileActivity) getActivity();
            presenter = new ChargingPilePresenter(parentActivity.getScheduler());
            presenter.setView(this);
            presenter.getChargingPileList();
        }
    }

    public boolean isCadillac() {
        Vehicle vehicle = ApplicationUtil.getInstance().getCurrentVehicle();
        if (vehicle == null)
            return false;
        String desc = vehicle.getModelDesc();
        return desc.contains("凯迪拉克") || desc.toLowerCase().contains("Cadillac".toLowerCase());
    }

    public boolean isBuick() {
        Vehicle vehicle = ApplicationUtil.getInstance().getCurrentVehicle();
        if (vehicle == null)
            return false;
        String desc = vehicle.getModelDesc();
        return desc.contains("别克") || desc.toLowerCase().contains("Buick".toLowerCase());
    }


    private void initListener() {
        edit_search_addressinfo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    isFirst = true;
                    presenter.getCurrentLocation();
                    presenter.clean();
                    presenter.getChargingPileList(edit_search_addressinfo.getText().toString());
                    CommonUtil.hideKeyBoard(baseActivity, edit_search_addressinfo);
                    return true;
                }
                return false;
            }
        });

        station_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //跳转到站点位置页面
                parentActivity.hideSoftInput();
                presenter.onItemClick(position);
            }
        });

        station_list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//                lastItemIndex = firstVisibleItem + visibleItemCount;
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        isFirst = false;
                        presenter.onScrollStateChanged(view);
                        break;
                }
            }
        });

        mBrandBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChargingPileBrandFragment brandFragment = new ChargingPileBrandFragment();
                baseActivity.changeFragment(baseActivity.getSupportFragmentManager(), brandFragment,
                        ChargingPileBrandFragment.class, false);
            }
        });
    }

    @Override
    public void setLoading(boolean isLoading) {
        if (isFirst) {
            loading_progress.setVisibility(isLoading ? View.VISIBLE : View.GONE);
            more_layout.setVisibility(View.GONE);
        } else {
            loading_progress.setVisibility(View.GONE);
            more_layout.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void showEmpty() {
        no_datas_layout.setVisibility(View.VISIBLE);
        no_datas_layout.setHintText("没有找到相关数据");
    }

    @Override
    public void onResponseError(OnStarException e) {
//        package_list_progress.setVisibility(View.GONE);
//


        station_list.setVisibility(View.GONE);
        no_datas_layout.setVisibility(View.VISIBLE);
        if (!CommonUtil.isNull(e.getMessage())) {
            no_datas_layout.setHintText(e.getMessage());
        } else {
            no_datas_layout.setHintText(R.string.no_set_meal_data_error);
        }
    }

    @Override
    public void onReponseSuccess(List<ChargePileStationEntity> object) {
        if (object != null && object.size() > 0) {
            no_datas_layout.setVisibility(View.GONE);
            adapter = new ChargePileStationListAdapter(object, parentActivity);
            station_list.setAdapter(adapter);
            station_list.setVisibility(View.VISIBLE);
        } else {
            station_list.setVisibility(View.GONE);
            no_datas_layout.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.no_datas_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.no_datas_layout://加载数据失败都点击屏幕重新加载
                no_datas_layout.setVisibility(View.GONE);
                presenter.getChargingPileList(edit_search_addressinfo.getText().toString());
                break;
        }
    }


    @Override
    public Activity onActivity() {
        return getActivity();
    }

    @Override
    public void previewCheck(boolean isHasMore) {
        more_layout.setVisibility(View.VISIBLE);
        if (!isHasMore) {
            tv_more.setText("没有更多的数据了");
        }
    }

    @Override
    public void onFailed(List<ChargePileStationEntity> chargePileStationEntityList, boolean isHaveNextPages, String err) {
        if (!CommonUtil.isNull(chargePileStationEntityList) && chargePileStationEntityList.size() > 0) {
            //加载失败
            edit_search_addressinfo.setText("");
            more_layout.setVisibility(View.VISIBLE);
            if (!isHaveNextPages) {
                tv_more.setText("信息加载时出错了，请重试一下");
            }
        } else {
//            ToastUtil.show(baseActivity,err);
            no_datas_layout.setVisibility(View.VISIBLE);
            no_datas_layout.setHintText(R.string.loadfailed_and_to_retry);
            station_list.setVisibility(View.GONE);
        }
    }
}
